package com.example.om_export.app.report.service;

import com.example.om_export.app.report.dao.ReportTemplateMapper;
import com.example.om_export.app.report.entity.ReportTemplate;
import com.example.om_export.common.entity.Params;
import com.example.om_export.common.entity.Result;
import com.example.om_export.common.utils.LayuiDataGrid;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@Service
public class ReportTemplateService {
    @Autowired

    ReportTemplateMapper rtm;

    public Result save(ReportTemplate report){
        if(StringUtils.isEmpty(report.getId())) {
            report.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            return Result.byRow(rtm.insert(report));
        }else {
            return Result.byRow(rtm.updateByPrimaryKey(report));
        }

    }

    public Result delete(String id){
        return Result.byRow(rtm.deleteByPrimaryKey(id));
    }


    /**
     * 格式化json 输出消息
     * @param response
     * @param msg
     */
    public static void jsonMsg(HttpServletResponse response, String msg, boolean success){
        PrintWriter out = null;
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        try {
            String jsonStr = "{\"success\":"+success+",\"msg\":\""+msg+"\"}";
            out = response.getWriter();
            out.write(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }

    public ReportTemplate getReportTemplateById(String templateId) {
        return rtm.selectByPrimaryKey(templateId);
    }

    public LayuiDataGrid getList(Integer page, Integer limit) {
        Page<Object> pageInfo = PageHelper.startPage(page, limit);
        rtm.selectByParams();
        return LayuiDataGrid.generate(pageInfo.getTotal(), pageInfo.getResult());
    }
}
